package com.ncloud.crm.service.impl;

import java.util.Date;
import java.util.List;

import com.ncloud.param.service.SequenceService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.common.Constant;
import com.ncloud.crm.entity.BsNodeNetAccess;
import com.ncloud.crm.entity.order.WorkNodeNetAccess;
import com.ncloud.crm.mapper.WorkNodeNetAccessMapper;
import com.ncloud.crm.service.BsNodeNetAccessService;
import com.ncloud.crm.service.WorkNodeNetAccessService;
import com.ncloud.crm.utils.DateUtils;
import com.ncloud.crm.utils.OrderNodeDefineUtils;
import com.ncloud.crm.utils.TableIdDefineUtils;

@Service
public class WorkNodeNetAccessServiceImpl implements WorkNodeNetAccessService {
	
	private static final Logger logger = LogManager.getLogger(WorkNodeNetAccessServiceImpl.class);
	
	@Autowired
	private WorkNodeNetAccessMapper WorkNodeNetAccessMapper;
    @Autowired
    private BsNodeNetAccessService bsNodeNetAccessService;
	@Reference
	private SequenceService sequenceService;


	public JSONArray getId(JSONObject json) {
		if(json==null || !json.containsKey("workId")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}
		List<WorkNodeNetAccess> orderAttrs = WorkNodeNetAccessMapper.getWorkNodeInterByWorkId(json.getLong("workId"));
		return JSON.parseArray(JSON.toJSONString(orderAttrs));
	}

	@Override
	public JSONObject getPk(JSONObject json) {
		return null;
	}

	@Override
	public JSONObject insert(JSONObject json) {

		WorkNodeNetAccess nodeEqpt = JSON.parseObject(json.toJSONString(),WorkNodeNetAccess.class);
		try {
			validation(nodeEqpt);
			WorkNodeNetAccessMapper.insertWorkNodeInter(nodeEqpt);
		}catch (RuntimeException e){
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return json;
	}
	private void validation(WorkNodeNetAccess nodeEqpt){
	    if(nodeEqpt.getIspInstId() ==null){
            Long id = sequenceService.getSequence("seq_isp_inst_id");
            nodeEqpt.setIspInstId(id);
        }
	}

	@Override
	public List<WorkNodeNetAccess> getNodeIntersByWorkId(Long workId) {
		return WorkNodeNetAccessMapper.getWorkNodeInterByWorkId(workId);
	}

	@Override
	public JSONObject validate(JSONObject json,JSONObject result) {
		JSONObject jsonObject = new JSONObject();
		return jsonObject;
	}

	@Override
	public void nodeNetAccess(JSONObject node,JSONObject result,JSONArray array){
		WorkNodeNetAccess workNodeNetAccess =null;
		//处理节点ispInfos
		if(node.containsKey("isp")) {
			JSONArray ispInfos = new JSONArray();
			JSONObject isp = node.getJSONObject("isp");
			ispInfos.add(isp);
			for (int k = 0; k < ispInfos.size(); k++) {
				JSONObject ispInfo = ispInfos.getJSONObject(k);
				//wan
				if(ispInfo.containsKey("wan")){
					JSONObject wanJson = ispInfo.getJSONObject("wan");
					WorkNodeNetAccess wanInter = JSON.parseObject(wanJson.toJSONString(), WorkNodeNetAccess.class);
					wanInter.setNetType("0");
					wanInter.setNetName("wan");

					/*保存信息*/
					getNetAccessByNetType(wanInter,node.getString("modifyTag"),array,result);
				}
				if(ispInfo.containsKey("lan")){
					JSONObject lanJson = ispInfo.getJSONObject("lan");
					WorkNodeNetAccess lanInter = JSON.parseObject(lanJson.toJSONString(), WorkNodeNetAccess.class);
					lanInter.setNetType("1");
					lanInter.setNetName("lan");
					if(StringUtils.isEmpty(lanInter.getIspName())){
						lanInter.setIspName("内部ISP");
					}
					/*保存信息*/
					getNetAccessByNetType(lanInter,node.getString("modifyTag"),array,result);
				}
			}
		}
	}

	private void getNetAccessByNetType(WorkNodeNetAccess workNodeNetAccess,String modifyTag,JSONArray array,JSONObject result){
		String eqptModifyTag = workNodeNetAccess.getModifyTag();
		if(StringUtils.isEmpty(eqptModifyTag)){
			eqptModifyTag =modifyTag;
		}
		workNodeNetAccess.setModifyTag(eqptModifyTag);

		if (workNodeNetAccess.getNodeId() == null) {
			workNodeNetAccess.setNodeId(result.getLong(TableIdDefineUtils.NODE_ID));
		}
		workNodeNetAccess.setWorkId(result.getLong(TableIdDefineUtils.WORK_ID));
		if (Constant.ADD.equals(eqptModifyTag)) {
			workNodeNetAccess.setBeginDate(DateUtils.parseDate(result.getString("createDate")));
			workNodeNetAccess.setEndDate(DateUtils.parseDate(Constant.END_DATE));
			workNodeNetAccess.setUpdateTime(DateUtils.parseDate(result.getString("createDate")));
			workNodeNetAccess.setUpdateUser(result.getLong("userID"));
		} else if (Constant.UPDATE.equals(eqptModifyTag)) {
                    /*根据修改的节点查询对应的实例信息，对实例做旧单操作，对改单做新增操作*/
			if(workNodeNetAccess.getIspInstId() !=null){
				BsNodeNetAccess bsNodeNetAccess = bsNodeNetAccessService.getNodeNetAccessOne(workNodeNetAccess.getIspInstId());
				logger.debug("旧isp信息："+JSON.toJSONString(bsNodeNetAccess));
				WorkNodeNetAccess workNodeNetAccessOld = JSON.parseObject(JSON.toJSONString(bsNodeNetAccess),WorkNodeNetAccess.class);
                        /*旧记录*/
				workNodeNetAccessOld.setEndDate(DateUtils.parseDate(result.getString("createDate")));
				workNodeNetAccessOld.setUpdateTime(DateUtils.parseDate(result.getString("createDate")));
				workNodeNetAccessOld.setUpdateUser(result.getLong("userID"));
				workNodeNetAccessOld.setWorkId(result.getLong(TableIdDefineUtils.WORK_ID));
				workNodeNetAccessOld.setModifyTag(Constant.DEL);
                        /*新记录*/

				//workNodeNetAccess.setWorkId(result.getLong(TableIdDefineUtils.WORK_ID));
				workNodeNetAccess.setBeginDate(DateUtils.parseDate(result.getString("createDate")));
				workNodeNetAccess.setEndDate(DateUtils.parseDate(Constant.END_DATE));
				workNodeNetAccess.setUpdateTime(DateUtils.parseDate(result.getString("createDate")));
				workNodeNetAccess.setUpdateUser(result.getLong("userID"));
				workNodeNetAccess.setModifyTag(Constant.ADD);
				array.add(JSON.parseObject(JSON.toJSONString(workNodeNetAccessOld)));
			}else {
				throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"ISP信息ispInstId不存在！");
			}

		}else if(Constant.DEL.equals(eqptModifyTag)){
			workNodeNetAccess.setEndDate(DateUtils.parseDate(result.getString("createDate")));
			workNodeNetAccess.setUpdateTime(DateUtils.parseDate(result.getString("createDate")));
			workNodeNetAccess.setUpdateUser(result.getLong("userID"));
		}else{
			workNodeNetAccess.setUpdateTime(DateUtils.parseDate(result.getString("createDate")));
			workNodeNetAccess.setUpdateUser(result.getLong("userID"));
		}
		//保存节点
		array.add(JSON.parseObject(JSON.toJSONString(workNodeNetAccess)));
	}

	@Override
	public List<WorkNodeNetAccess> getNewNodeIntersByWorkId(Long workId, Long nodeId) {
		return WorkNodeNetAccessMapper.getNewNodeIntersByWorkId(workId,nodeId);
	}
}
